<?php
	mysql_connect("localhost", "root", "%Tg34fv1")or die("cannot connect"); 
	mysql_select_db("wordWaffle")or die("cannot select DB");
	//make sure it's actually okay to join
	$result = mysql_query("SELECT * FROM gameStatus ORDER BY gameID DESC LIMIT 1");
	if (mysql_num_rows($result) == 0)
	{
		mysql_query("INSERT INTO gameStatus (status) VALUES (0)");
		$gameStatus['status'] = 0;
	}
	else
		$gameStatus = mysql_fetch_assoc($result);
		
	if ($gameStatus['status'] == 1)
	{
		echo "A game is currently in progress.  Please try again later.";
		return;
	}
	else
	{
		mysql_select_db("wordWaffle")or die("cannot select DB");
		//am I the first to join?
		if ($gameStatus['status'] > 1)
			mysql_query("INSERT INTO gameStatus (status) VALUES (0)");
			
		mysql_select_db("membersDB")or die("cannot select DB");
		$name = mysql_real_escape_string(stripslashes($_GET['name']));
		$password = mysql_real_escape_string(stripslashes($_GET['password']));
		$firsttime = mysql_real_escape_string(stripslashes($_GET['firsttime']));
		$myKey = mysql_real_escape_string(stripslashes($_GET['sesskey']));

		//check login
		$result=mysql_query("SELECT * FROM members WHERE memberName='$name'");
		if ($firsttime == "checked")
		{
			if (mysql_num_rows($result))
			{
				echo "This name is already taken.  Please choose a different one.";
				return;
			}
			else //enter it into the database
			{
				mysql_query("INSERT INTO members (memberName,memberPassword) VALUES ('$name','$password')");
				$result = mysql_query("SELECT * FROM members WHERE memberName='$name'");
				$row = mysql_fetch_assoc($result);
			}
		}
		else
		{
			//ensure password is correct
			$row = mysql_fetch_assoc($result);
			if ($row['memberPassword'] != $password)
			{
				echo "Login failed";
				return;
			}
		}
		
		session_start();
		$_SESSION['playerName'] = $name;
		$_SESSION['password'] = $password;
		
		mysql_query("INSERT INTO players (memberID,playerName,sesskey,readyToPlay) VALUES (" .$row['memberID'] . ",'$name',$myKey,1)");
		$result = mysql_query("SELECT * FROM gameStatus ORDER BY gameID DESC LIMIT 1");
		$row = mysql_fetch_assoc($result);
		echo $row['gameID'];
		return;
	}
?>